#!/bin/sh

# Start and stop openlava daemons
# Run by hand or install in /etc/init.d
# and make a symbolic link from rc3.d to it.
#
# The following is for the Linux chkconfig utlility
# chkconfig: 35 99 01
# description: openlava

### BEGIN INIT INFO
# Provides: openlava
# Required-Start: $local_fs $remote_fs $network $syslog 
# Required-Stop: $local_fs $remote_fs $syslog $network
# Default-Start:  3 4 5
# Default-Stop: 0 1 6
# Short-Description: openlava
# Description: openlava is a distributed batch system
### END INIT INFO

# This is the root of openlava installation
# change it if installed somewhere else.
export OPENLAVA_TOP=@prefix@

# kill the old daemons first.
#
kill_daemons()
{
    killall -q lim res sbatchd  mbatchd
}

# Restart is just like start since in both
# cases previously running daemons are 
# killed.
opcode="$1"
if [ "$opcode" = "restart" ]
then 
   opcode="start"
   echo "Stopping daemons..."
fi

# Process the requested operation.
case "$opcode" in
  'stop')
        echo "Stopping daemons..."
        kill_daemons
        exit 0
        ;;

  'start')
        LSF_CONF=$OPENLAVA_TOP/etc/lsf.conf

        if [ -f $LSF_CONF ]
        then
            kill_daemons

            # Get the location of the openlava daemons
            . $LSF_CONF

            # Export this env.variable to notify openlava daemons the loc. of
            # lsf.conf
            export LSF_ENVDIR
            export LSF_SERVERDIR
            echo "Starting daemons..."

	    ID=`id -u`
            if [ "$ID" != 0 ]; then
            # single user mode use this
            # to run test clusters
               $LSF_SERVERDIR/lim -1
               echo "lim -1 started"
               $LSF_SERVERDIR/res -1
               echo "res -1 started"
               $LSF_SERVERDIR/sbatchd -1
               echo "sbatchd -1 started"
            else
               # multi user mode
               $LSF_SERVERDIR/lim
               echo "lim started"
               $LSF_SERVERDIR/res
               echo "res started"
               $LSF_SERVERDIR/sbatchd
               echo "sbatchd started"
            fi
            exit 0
        fi
        echo "$LSF_CONF: no such file or directory"
        exit 1
        ;;
  'status')
        PID=`pidof lim`
        echo "lim pid: <$PID>"
        PID=`pidof res`
        echo "res pid: <$PID>"
        PID=`pidof sbatchd`
        echo "sbatchd pid: <$PID>"
        PID=`pidof mbatchd`
        echo "lim mbatchd: <$PID>"
        exit 0
        ;;
  *)
        echo "Script for starting up and shutting down openlava"
        echo "Usage: $0 { start | stop | status | restart }"
        exit 0
        ;;
esac

